#pragma once
#include <iostream>
#include <string>
#include <memory>
#include "Socket.hpp"
#include <jsoncpp/json/json.h>
#include <functional>

using namespace SocketModule;

// 实现一个自定义的网络版本的计算器

// client -> server
// content_len
// 50\r\n{"x":10,"y":20,"oper":'+'}\r\n
class Request
{
public:
    Request() {}
    Request(int x, int y, char oper)
        : _x(x), _y(y), _oper(oper)
    {
    }
    std::string Serialize()
    {
        std::string s;
        Json::Value root;
        root["x"] = _x;
        root["y"] = _y;
        root["oper"] = _oper;

        Json::FastWriter writer;
        s = writer.write(root);
        return s;
    }
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt(); // ?
        }
        return ok;
    }
    ~Request() {}
    int X() { return _x; }
    int Y() { return _y; }
    char Oper() { return _oper; }

private:
    int _x;
    int _y;
    char _oper; // + - * / %
};

// server -> client
class Response
{
public:
    Response() {}
    Response(int result, int code)
        : _result(result), _code(code)
    {
    }
    std::string Serialize()
    {
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;

        Json::FastWriter writer;
        std::string s = writer.write(root);
        return s;
    }
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _result = root["result"].asInt();
            _code = root["code"].asInt();
        }
        return ok;
    }
    ~Response() {}
    void SetResult(int res)
    {
        _result = res;
    }
    void SetCode(int code)
    {
        _code = code;
    }

private:
    int _result; // 无法区分计算结果和异常
    int _code;   // 0:success,   1.2.3.4->异常
};

const std::string sep = "\r\n";

using func_t = std::function<Response(Request &req)>;

// 两个问题（基于tcp），
// 1.request和response必须得有序列化和反序列化功能
// 2.保证读取时读到完整报文（只考虑tcp，UDP不需要考虑）
class Protocol
{
public:
    Protocol(func_t func)
        : _func(func)
    {
    }
    std::string Encode(const std::string jsonstring)
    {
        std::string len = std::to_string(jsonstring.size());
        return len + sep + jsonstring + sep;
    }

    bool Decode(std::string &buffer, std::string *package)
    {
        ssize_t pos = buffer.find(sep);
        if (pos == std::string::npos)
            return false;
        std::string package_len_str = buffer.substr(0, pos);
        int package_len_int = std::stoi(package_len_str);

        int target_len = package_len_str.size() + package_len_int + 2 * sep.size();
        if (buffer.size() < target_len)
            return false;

        *package = buffer.substr(pos + sep.size(), package_len_int);
        buffer.erase(0, target_len);
        return true;
    }

    void GetRequest(std::shared_ptr<Socket> &sock, InetAddr &client)
    {
        std::string buffer_queue;
        while (true)
        {
            int n = sock->Recv(&buffer_queue);
            if (n > 0)
            {
                std::string json_package;
                bool ret = Decode(buffer_queue, &json_package);
                if (!ret)
                    continue;

                Request req;
                bool ok = req.Deserialize(json_package);
                if (!ok)
                    continue;

                Response resp = _func(req);

                std::string json_str = resp.Serialize();

                std::string send_str = Encode(json_str);

                sock->Send(send_str);
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client:" << client.StringAddr() << "Quit!";
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "client:" << client.StringAddr() << ", recv Error!";
                break;
            }
        }
    }
    ~Protocol()
    {
    }

private:
    // Request _req;
    // Response _resp;
    func_t _func;
};